<?php
namespace Home\Controller;
use Think\Controller;
class LoginController extends Controller {
    public function login(){
        if (IS_POST) {
            //接收数据
            $username = I('post.username');
            $userpwd = I('post.userpwd');
            $code = I('post.verify'); 
            
            //验证码验证
            $verify = new \Think\Verify();
            if(!$verify->check($code,$id)){
                $this->error('验证码不正确');
            } 
            
            //账号密码验证 
            $user = M('User');
            $where['username'] = $username;
            $where['userpwd'] = md5($userpwd);
            $arr = $user->field('id')->where($where)->find();
            //如果查询出错，find方法返回false，如果查询结果为空返回NULL，查询成功则返回一个关联数组（键值是字段名或者别名）。
            if (is_array($arr)) {
                //写入SESSION
                $_SESSION['username'] = $username;
                $_SESSION['userid'] = $arr['id'];
                $this->success('用户登陆成功',U('Index/index'));
            }else{//不存在显示错误消息
                $this->error('操作出错或该用户不存在');
            }

        }else{
            $this->display();
        }
    }    
    public function logout(){
        $_SESSION = array();
        if (isset($_COOKIE[session_name()])) {//如果把当前session的索引保存在cookie中了也要清空
            setcookie(session_name(),'',time()-1,'/');
        }
        session_destroy();
        $this->success('退出成功',U('Index/index'));
        //$this->redirect('Admin/Index/index', array('test' => 2), 5, '页面跳转中...');
    }
}
